<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\analysis\report\ocean;

use app\enum\AnalysisEnum;
use app\model\mongo\MongoOePicDayReportModel;
use app\model\mongo\MongoOePicModel;
use app\model\mongo\MongoReportModel;
use app\service\analysis\OceanTrait;
use app\service\analysis\report\ReportInterface;
use app\service\analysis\report\ReportService;

class PicReportService extends ReportService implements ReportInterface
{
    use OceanTrait;

    /**
     * @var int 同步类型
     */
    protected static int $taskType = AnalysisEnum::TASK_TYPE_PICTURE;

    /**
     * 账户总消耗.
     * @param array $where 查询参数
     * @return float[]
     */
    public function getAccountStat(array $where = []): array
    {
        $model = new MongoOePicDayReportModel();
        $res = $model->cmd([
            'aggregate' => $model->getTable(),
            'pipeline' => [
                [
                    '$match' => $where,
                ],
                [
                    '$group' => [
                        '_id' => null,
                        'totalCost' => ['$sum' => '$cost'],
                    ],
                ],
                [
                    '$project' => [
                        '_id' => 1,
                        'totalCost' => 1,
                    ],
                ],
            ],
            'cursor' => new \stdClass(),
            'explain' => false,
        ]);
        $data = $res[0] ?? [];
        return [
            'cost' => $this->getTotalCost($data),
        ];
    }

    /**
     * 获取账户消耗.
     * @param array $where 查询条件
     */
    public static function getSignatureCost(array $where = []): float
    {
        $cost = self::getModel()->where($where)->sum('cost');
        return floatval(bcadd(strval($cost), '0', 2));
    }

    /**
     * 获取消耗.
     *
     * @param array $data 数据
     */
    private function getTotalCost(array $data = []): float
    {
        $cost = $data['totalCost'] ?? 0;
        return floatval(bcadd(strval($cost), '0', 2));
    }


    /**
     * 获取数据MD5值
     * @param MongoReportModel $model
     * @param string $field
     * @return mixed
     */
    public function getReportAttr(MongoReportModel $model, string $field=''){
        $obj = (new MongoOePicModel())
            ->where('account_id',$model->getAttr('account_id'))
            ->where('material_id',$model->getAttr('pic_id'))
            ->findOrEmpty();
        return $obj->getAttr($field);
    }
}
